﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WAU.DTOs;
using WAU.DTOs.OrderModule;
using WAU.Models.Framework;
using WAU.Services;

namespace WAU.Controllers
{
    /// <summary>
    /// 订单相关控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class OrderController : EssentialController
    {
        private OrderService _orderService;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="orderService"></param>
        public OrderController(OrderService orderService)
        {
            _orderService = orderService;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> CreateNewOrder(CreateNewOrderDto dto)
        {
            ExecResult execResult = _orderService.CreateNewOrderRedisLua(CurrentUserId, dto);
            execResult = await Task.FromResult(execResult);
            if (execResult.Success)
            {
                return Ok(new Result
                {
                    Success = true,
                    Msg = execResult.ErrorMsg
                });
            }
            else
            {
                return StatusCode(500, new Result
                {
                    Success = false,
                    Msg = execResult.ErrorMsg
                });
            }
        }
        /// <summary>
        /// 创建订单（内存锁）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> CreateNewOrderLocalLock(CreateNewOrderDto dto)
        {
            ExecResult execResult = _orderService.CreateNewOrderLocalLock(CurrentUserId, dto);
            execResult = await Task.FromResult(execResult);
            if (execResult.Success)
            {
                return Ok(new Result
                {
                    Success = true,
                    Msg = execResult.ErrorMsg
                });
            }
            else
            {
                return StatusCode(500, new Result
                {
                    Success = false,
                    Msg = execResult.ErrorMsg
                });
            }
        }

        /// <summary>
        /// 库存数据写入 Redis
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetStockToRedis(BaseIdDto dto)
        {
            ExecResult execResult = _orderService.SetStockToRedis(dto.Id);
            return Ok(new Result
            {
                Success = execResult.Success,
                Msg = execResult.ErrorMsg
            });
        }
    }
}
